package com.example.fangyimanagement.core;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import javax.annotation.Nonnull;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 安全拦截器
 */
@Component
public class SecurityInterceptor implements HandlerInterceptor {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private static final Logger logger = LoggerFactory.getLogger(SecurityInterceptor.class);

    public static final String LOGIN_USER_KEY = "login_user_key";

    @Override
    public boolean preHandle(@Nonnull HttpServletRequest request, @Nonnull HttpServletResponse response, @Nonnull Object handler) {
        // 忽略options请求
        if ("OPTIONS".equals(request.getMethod())) {
            // addHeaders(request);
            return false;
        }

        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            throw new BizException("请先登录");
        }
        /**
         * 先校验是不是管理端用户登录的
         */
        List<Map<String, Object>> userList = this.jdbcTemplate.queryForList("SELECT * FROM glpt_user WHERE token = ?", token);
        if (userList.isEmpty()) {
            /**
             * 如果管理端没查到，再去查移动端
             */
            List<Map<String, Object>> mobileUserList = this.jdbcTemplate.queryForList("SELECT * FROM mobile_user WHERE token = ?", token);
            if (mobileUserList.isEmpty()) {
                throw new BizException("token无效");
            }
            Map<String, Object> mobileUserInfo = mobileUserList.get(0);
            Date tokenCreateTime = (Date) mobileUserInfo.get("token_create_time");
            if (DateTime.now().between(tokenCreateTime, DateUnit.HOUR) >= 1) {
                throw new BizException("登录已过期");
            }
            this.jdbcTemplate.update("UPDATE mobile_user SET token_create_time=? WHERE token=?", new Date(), token);
            request.setAttribute(
                    LOGIN_USER_KEY,
                    new LoginUser()
                            .setId(Long.parseLong(mobileUserInfo.get("id").toString()))
                            .setName(mobileUserInfo.get("name").toString())
                            .setAccount(mobileUserInfo.get("sfz").toString())
            );
        } else {
            /**
             * 是管理端用户
             */
            Map<String, Object> userInfo = userList.get(0);
            Date tokenCreateTime = (Date) userInfo.get("token_create_time");
            if (DateTime.now().between(tokenCreateTime, DateUnit.HOUR) >= 1) {
                throw new BizException("登录已过期");
            }
            this.jdbcTemplate.update("UPDATE glpt_user SET token_create_time=? WHERE token=?", new Date(), token);
            request.setAttribute(
                    LOGIN_USER_KEY,
                    new LoginUser()
                            .setId(Long.parseLong(userInfo.get("id").toString()))
                            .setName(userInfo.get("name").toString())
                            .setAccount(userInfo.get("account").toString())
            );
        }

        return true;
    }

    @Override
    public void postHandle(@Nonnull HttpServletRequest httpRequest, @Nonnull HttpServletResponse response, @Nonnull Object handler, ModelAndView modelAndView) {

    }
}
